import processing.serial.*;
import controlP5.*;
import processing.net.*;


ControlP5 controlP5;
Button bFill;
Button bWeigh;
Button bDone;
Radio r;
Serial port;

PFont theFont;
// 0 none
// 1 Filling
// 2 Weigh
int state; 
int currentId = 0;
Client myClient;

final int SERVER_PORT		= 28000;

void setup()  {
  size(550, 300);
  controlP5 = new ControlP5(this);
  bFill = controlP5.addButton("Fill", 0, 50, 100, 200, 50);
  bWeigh = controlP5.addButton("Weigh", 1, 300, 100, 200, 50);
  bDone = controlP5.addButton("Done", 2, 175, 200, 200, 50);
  bDone.hide();
  port = new Serial(this, Serial.list()[0], 9600);
  theFont = createFont("Helvetica", 32);
  textFont(theFont);
  textAlign(CENTER, CENTER);
  state = 0;
  
  r = controlP5.addRadio("radio",175,200);
  r.add("Food Dish 1",0);
  r.add("Food Dish 2",1);
  
  myClient = new Client(this, "131.193.77.183", SERVER_PORT);
  
}

void draw() {
  background(0);
  fill(255);
  if( port.available() > 0 ) {
    char res = (char) port.read();
    println("read: " + res);
    if( res == 'F' ) {
      bFill.hide();
      bWeigh.hide();
      r.hide();
      bDone.show();
      state = 1;
    }
    else if (res == 'G') {
      while(port.available() <= 0) {
      }
      
      int fAmount = port.read();
      String data = "F," + currentId + "," + (fAmount + 1);
      println("Read: " + fAmount);
      
      delay(fAmount * 100);
      
      myClient.write(data);
      state = 0;
      bFill.show();
      bWeigh.show();
      r.show();
      bDone.hide();
    }
  }
  switch(state) {
    case 0:
    {
      break;
    }
    case 1:
    {
      text("Filling...", width / 2, height /2 );
      break;
    }
    case 2:
    {
      text("Weigh...", width / 2, height /2 );
      break;
    }
  }
}

public void Fill(int theValue) {
  port.write('F');
  state = 1;
  bFill.hide();
  bWeigh.hide();
  r.hide();
  bDone.show();
}

public void Weigh(int theValue) {
  port.write('W');
  state = 2;
  bFill.hide();
  bWeigh.hide();
  r.hide();
  bDone.show();
  
  String data;
  
  myClient.write("W," + currentId);
        
  while( myClient.available() < 5 ) { }
  data = myClient.readString();
  String[] res = split(data, ",");
        
  println(data);
        
  int amountLeft = Integer.parseInt(res[2]);
  //if( amountLeft != 0 ) amountLeft--;
  port.write( amountLeft );
  
}

public void Done(int theValue) {
  String data;
  
  if( state == 1 ) {
    port.write('G');
    
    while(port.available() <= 0) {
    }
    
    int fAmount = port.read();
    data = "F," + currentId + "," + (fAmount + 1);
    println("Read: " + fAmount);
    
    delay(fAmount * 1000);
    myClient.write(data);
  }
  else if( state == 2 ) {

  }
    

  
  port.write('D');
  state = 0;
  bFill.show();
  bWeigh.show();
  r.show();
  bDone.hide();
  //println("Once");
}

public void radio(int id) {
  currentId = id;
}


